﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeManageService;

namespace WeManageForm
{
    public partial class PlanManageForm : Form
	{
		private PlanQueryArgs queryArgs = new PlanQueryArgs();
		private bool dateRBtnSelected = false;      
        public static AutoCompleteStringCollection accs = new AutoCompleteStringCollection();
        public bool QueryTextClick = false;
		public bool Painted = false;
        public PlanManageForm()
        {
            InitializeComponent();
            DGVPlan.Columns[0].Visible = false;
            BtnChooseAll.Visible = false;
            BtnDeletePlan.Visible = false;
			DGVPlan.DataSource = BSPlan;
			DGVPlan.CellContentClick += PlanDetailBtnClick;
			DGVPlan.CellContentClick += PlanCheckClick;
			QueryText.GotFocus += QueryText_GotFocus;
			QueryText.LostFocus += QueryText_LostFocus;
			minDateTimePicker.ValueChanged += DateTimePicker_ValueChanged;
			maxDateTimePicker.ValueChanged += DateTimePicker_ValueChanged;
			RBtnDoneQuery.Click += PStateSelect;
			RBtnNoDoneQuery.Click += PStateSelect;
            QueryText.AutoCompleteCustomSource = accs;
			RefreshData();
			PlanManager.StartRefresh += RefreshData;
			System.Timers.Timer timer = new System.Timers.Timer(1);
			timer.Elapsed += (_1, _2) => DGVPlan.Invoke(new Action(() => RefreshData()));
			timer.AutoReset = false;
			timer.Enabled = true;
        }

        private void BtnManagePlan_Click(object sender, EventArgs e)
        {
            if (BtnManagePlan.Text == "管理")
            {
                BtnManagePlan.Text = "完成";
                BtnChooseAll.Text = "全选";
                BtnChooseAll.Visible = true;
                BtnDeletePlan.Visible = true;
                DGVPlan.Columns[0].Visible = true;
				RefreshData();
			}
            else
            {
                BtnManagePlan.Text = "管理";
                BtnChooseAll.Text = "全选";
                BtnChooseAll.Visible = false;
                BtnDeletePlan.Visible = false;
                DGVPlan.Columns[0].Visible = false;
            }
        }

        private void BtnAddPlan_Click(object sender, EventArgs e)
        {
            PlanForm planForm = new PlanForm(0);
            planForm.StartPosition = FormStartPosition.CenterParent;
			planForm.FormClosing += (S,E) => RefreshData();
			planForm.ShowDialog();
        }

		private void RefreshData()
		{
			Painted = true;
			BSPlan.DataSource = PlanManager.QueryPlan(queryArgs);

			DataGridViewCellStyle DisableStyle = new DataGridViewCellStyle() { BackColor = SystemColors.ControlDark, SelectionBackColor = SystemColors.ControlDark };
			DataGridViewCellStyle FinishStyle = new DataGridViewCellStyle() { BackColor = Color.Aqua };
			DataGridViewCellStyle TLEStyle = new DataGridViewCellStyle() { BackColor = Color.OrangeRed };
			
			foreach (DataGridViewRow i in DGVPlan.Rows)
			{
				foreach (DataGridViewCell j in i.Cells)
				{
					if (j.OwningColumn.Name == "PlanID")
					{
						int id = (int)j.Value;
						Plan plan = PlanManager.GetPlanClone(id);
						foreach(DataGridViewCell k in i.Cells)
						{
							if(k.OwningColumn.Name == "check")
							{
								if (plan.PState != 0 || !plan.Deletable)
								{
									k.Style = DisableStyle;
									k.ReadOnly = true;
								}
							}
							else
							{
								if (plan.PState == 1) k.Style = FinishStyle;
								else if (plan.PState == 2) k.Style = TLEStyle;
							}
						}
					}
				}
			}
			Painted = false;
		}

		private void BtnChooseAll_Click(object sender, EventArgs e)
		{
            if(BtnChooseAll.Text == "全选")
            {
                BtnChooseAll.Text = "取消";
                RefreshData();
                foreach (DataGridViewRow i in DGVPlan.Rows)
                {
                    foreach (DataGridViewCell j in i.Cells)
                    {
                        if (j.OwningColumn.Name == "check")
                        {
							if(j.Style.BackColor != SystemColors.ControlDark)
								(j as DataGridViewCheckBoxCell).Value = true;
							break;
						}
                    }
                }
            }
            else
            {
                BtnChooseAll.Text = "全选";
				RefreshData();
				foreach (DataGridViewRow i in DGVPlan.Rows)
				{
					foreach (DataGridViewCell j in i.Cells)
					{
						if (j.OwningColumn.Name == "check")
						{
							(j as DataGridViewCheckBoxCell).Value = false;
							break;
						}
					}
				}

			}
		}

		private void BtnDeletePlan_Click(object sender, EventArgs e)
		{
			foreach (DataGridViewRow i in DGVPlan.Rows)
			{
				bool? check = null;
				int? id = null;
				foreach (DataGridViewCell j in i.Cells)
				{
					if(j.OwningColumn.Name == "check")
					{
						check = j.Value as bool?;
					}
					else if(j.OwningColumn.Name == "PlanID")
					{
						id = j.Value as int?;
					}
					if (check != null && id != null)
					{
						if ((bool)check) PlanManager.DeletePlan((int)id);
						break;
					}
				}
			}
			RefreshData();
		}

        //点击显示接下来一个月
        private void RBtnMonthQuery_CheckedChanged(object sender, EventArgs e)
		{
			dateRBtnSelected = true;
			DateTime now = DateTime.Now;
			minDateTimePicker.Value = new DateTime(now.Year, now.Month, now.Day);
			maxDateTimePicker.Value = minDateTimePicker.Value.AddMonths(1).AddDays(-1);
			RefreshData();
			dateRBtnSelected = false;
		}


        //点击显示接下来一周
        private void RBtnWeekQuery_CheckedChanged(object sender, EventArgs e)
		{
			dateRBtnSelected = true;
			DateTime now = DateTime.Now;
			minDateTimePicker.Value = new DateTime(now.Year, now.Month, now.Day);
			maxDateTimePicker.Value = minDateTimePicker.Value.AddDays(6);
			RefreshData();
			dateRBtnSelected = false;
		}

        //点击正则查询
        private void BtnDetailQuery_Click(object sender, EventArgs e)
        {
            foreach (string s in accs)
            {
                if (accs.IndexOf(QueryText.Text) == -1)
                {
                    accs.Add(QueryText.Text);
                }
            }
            QueryText.AutoCompleteCustomSource = accs;
            if (QueryText.ForeColor == SystemColors.GrayText) queryArgs.RegexString = "";
			else queryArgs.RegexString = QueryText.Text;
			queryArgs.QueryTimeType = -1;
			RefreshData();
		}

        //根据正则表达式和两个date检索日期在这段时间的任务
        private void BtnShowResult_Click(object sender, EventArgs e)
		{
			if (QueryText.ForeColor == SystemColors.GrayText) queryArgs.RegexString = "";
			else queryArgs.RegexString = QueryText.Text;
			queryArgs.QueryTimeType = 1;
			DateTime v = minDateTimePicker.Value;
			queryArgs.MinTime = new DateTime(v.Year, v.Month, v.Day);
			v = maxDateTimePicker.Value;
			queryArgs.MaxTime = new DateTime(v.Year, v.Month, v.Day).AddDays(1).AddSeconds(-1);
			RefreshData();
        }

		private void PlanDetailBtnClick(object sender, DataGridViewCellEventArgs e)
		{
			if (DGVPlan.Columns[e.ColumnIndex].Name == "DetailBtn")
			{
				if (e.RowIndex == -1) return;
				foreach (DataGridViewCell cell in DGVPlan.Rows[e.RowIndex].Cells)
				{
					if (cell.OwningColumn.DataPropertyName == "PlanID")
					{
						Plan plan = PlanManager.GetPlanClone((int)cell.Value);
						PlanForm form = new PlanForm(1, plan);
						form.Closed += (_1, _2) => RefreshData();
                        form.ShowDialog();
					}
				}
			}
		}
		
		private void PlanCheckClick(object sender, DataGridViewCellEventArgs e)
		{
			if (DGVPlan.Columns[e.ColumnIndex].Name == "check" && e.RowIndex != -1)
				BtnChooseAll.Text = "全选";
		}

		private void QueryText_GotFocus(object sender, EventArgs e)
		{
			if(QueryText.ForeColor == SystemColors.GrayText)
			{
				QueryText.Text = "";
				QueryText.ForeColor = SystemColors.ControlText;
			}
		}

		private void QueryText_LostFocus(object sender, EventArgs e)
		{
			if (QueryText.Text == "")
			{
				QueryText.ForeColor = SystemColors.GrayText;
				QueryText.Text = "<正则匹配>";
			}
		}

		private void DateTimePicker_ValueChanged(object sender, EventArgs e)
		{
			if (!dateRBtnSelected)
			{
				RBtnMonthQuery.Checked = false;
				RBtnWeekQuery.Checked = false;
			}
		}

		private void PStateSelect(object sender, EventArgs e)
		{
			if ((sender as RadioButton).Text == "已完成")
			{
				if (queryArgs.PState == 1) queryArgs.PState = -1;
				else queryArgs.PState = 1;
			}
			else
			{
				if (queryArgs.PState == 0) queryArgs.PState = -1;
				else queryArgs.PState = 0;
			}
			switch (queryArgs.PState)
			{
				case -1: (sender as RadioButton).Checked = false; break;
				case 0: RBtnNoDoneQuery.Checked = true; break;
				case 1: RBtnDoneQuery.Checked = true; break;
			}
			RefreshData();
		}


        private void QueryText_Click(object sender, EventArgs e)
        {
            if (!QueryTextClick)
            {
                QueryTextClick = true;
                QueryText.SelectAll();
            }
            else
                QueryText.Select();
        }

        private void QueryText_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Control || e.KeyCode == Keys.Enter)
            {
                foreach (String s in accs)
                {
                    if (accs.IndexOf(QueryText.Text) == -1)
                    {
                        accs.Add(QueryText.Text);
                    }
                }
                QueryText.AutoCompleteCustomSource = accs;
                if (QueryText.ForeColor == SystemColors.GrayText) queryArgs.RegexString = "";
                else queryArgs.RegexString = QueryText.Text;
                queryArgs.QueryTimeType = -1;
                RefreshData();
            }
        }

        private void BtnReset_Click(object sender, EventArgs e)
        {
			minDateTimePicker.Value = maxDateTimePicker.Value = DateTime.Now;
			QueryText.Text = "<正则匹配>";
			QueryText.ForeColor = SystemColors.GrayText;
			RBtnDoneQuery.Checked = false;
			RBtnNoDoneQuery.Checked = false;
			RBtnMonthQuery.Checked = false;
			RBtnWeekQuery.Checked = false;
			queryArgs = new PlanQueryArgs();
			RefreshData();
        }
    }
}
